package com.bycx.wechat.util;

import com.bycx.core.startup.AppConfig;
import com.bycx.core.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 签名算法
 * @author hc
 * 2017年7月10日
 */
public class WeChatSignUtil {
	//先获取到jsapi_ticket的值,再调用
	public static Map<String, String> sign(String url,String jsapi_ticket) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        String appId = AppConfig.get("wx_appid");
        String secret = AppConfig.get("wx_appsecret");
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
       // System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        
        ret.put("secret", secret);
        ret.put("appId", appId);
        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("noncestr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        /*System.out.println("url = "+ url +"\n"+
        					"jsapi_ticket = " + jsapi_ticket +"\n"+
        					"nonceStr = " + nonce_str +"\n"+
        					"timestamp = " + timestamp +"\n"+
        					"signature = " + signature +"\n"
        				  );*/
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return StringUtils.getUUID();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
